<template>
  <div class="post-detail">
    <el-skeleton :loading="loading" animated>
      <template #template>
        <div class="skeleton-content">
          <el-skeleton-item variant="h1" style="width: 60%" />
          <el-skeleton-item variant="text" style="width: 40%; margin-top: 16px" />
          <el-skeleton-item variant="text" style="width: 100%; margin-top: 16px" />
          <el-skeleton-item variant="text" style="width: 80%; margin-top: 8px" />
          <el-skeleton-item variant="image" style="width: 100%; height: 300px; margin-top: 16px" />
        </div>
      </template>

      <template #default>
        <div v-if="post" class="post-content card">
          <!-- 帖子头部 -->
          <div class="post-header">
            <div class="user-info">
              <el-avatar :size="50" :src="post.user.avatar">
                {{ post.user.username.charAt(0) }}
              </el-avatar>
              <div class="user-details">
                <div class="username">{{ post.user.username }}</div>
                <div class="post-meta">
                  <span>{{ formatTime(post.createTime) }}</span>
                  <el-tag v-if="post.category" size="small" type="info">
                    {{ post.category.name }}
                  </el-tag>
                </div>
              </div>
            </div>
            
            <el-dropdown v-if="canEdit">
              <el-button text>
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="editPost">编辑</el-dropdown-item>
                  <el-dropdown-item @click="deletePost">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <!-- 帖子内容 -->
          <div class="post-body">
            <h1 class="post-title">{{ post.title }}</h1>
            <div class="post-text">{{ post.content }}</div>
            
            <!-- 图片展示 -->
            <div v-if="post.images && post.images.length > 0" class="post-images">
              <el-image
                v-for="(image, index) in post.images"
                :key="index"
                :src="image"
                class="post-image"
                fit="cover"
                :preview-src-list="post.images"
                :initial-index="index"
              />
            </div>
          </div>

          <!-- 帖子操作 -->
          <div class="post-actions">
            <el-button
              :type="post.isLiked ? 'danger' : 'info'"
              text
              @click="toggleLike"
            >
              <el-icon><Heart /></el-icon>
              {{ post.likesCount }}
            </el-button>
            
            <el-button text type="info">
              <el-icon><ChatLineRound /></el-icon>
              {{ post.commentsCount }}
            </el-button>
            
            <el-button text type="info">
              <el-icon><View /></el-icon>
              {{ post.viewsCount }}
            </el-button>
            
            <el-button text type="info" @click="sharePost">
              <el-icon><Share /></el-icon>
              分享
            </el-button>
          </div>
        </div>

        <!-- 评论区 -->
        <div class="comments-section card">
          <div class="comments-header">
            <h3>评论 ({{ comments.length }})</h3>
          </div>

          <!-- 发表评论 -->
          <div v-if="userStore.isLoggedIn" class="comment-form">
            <el-input
              v-model="newComment"
              type="textarea"
              placeholder="发表你的看法..."
              :rows="3"
              maxlength="500"
              show-word-limit
            />
            <div class="comment-actions">
              <el-button type="primary" @click="submitComment" :loading="commentLoading">
                发表评论
              </el-button>
            </div>
          </div>
          
          <div v-else class="login-prompt">
            <p>登录后可发表评论</p>
            <el-button type="primary" @click="goToLogin">登录</el-button>
          </div>

          <!-- 评论列表 -->
          <div class="comments-list">
            <div v-if="comments.length === 0" class="empty-comments">
              <el-empty description="暂无评论，来发表第一条评论吧！" />
            </div>
            
            <div v-else>
              <div v-for="comment in comments" :key="comment.id" class="comment-item">
                <el-avatar :size="40" :src="comment.user.avatar">
                  {{ comment.user.username.charAt(0) }}
                </el-avatar>
                
                <div class="comment-content">
                  <div class="comment-header">
                    <span class="comment-author">{{ comment.user.username }}</span>
                    <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
                  </div>
                  
                  <div class="comment-text">{{ comment.content }}</div>
                  
                  <div class="comment-actions">
                    <el-button text size="small" @click="likeComment(comment)">
                      <el-icon><Heart /></el-icon>
                      {{ comment.likesCount || 0 }}
                    </el-button>
                    <el-button text size="small" @click="replyComment(comment)">
                      <el-icon><ChatLineRound /></el-icon>
                      回复
                    </el-button>
                  </div>

                  <!-- 子评论 -->
                  <div v-if="comment.replies && comment.replies.length > 0" class="replies">
                    <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                      <el-avatar :size="32" :src="reply.user.avatar">
                        {{ reply.user.username.charAt(0) }}
                      </el-avatar>
                      <div class="reply-content">
                        <span class="reply-author">{{ reply.user.username }}</span>
                        <span class="reply-text">{{ reply.content }}</span>
                        <span class="reply-time">{{ formatTime(reply.createTime) }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </el-skeleton>
    
    <!-- 发布帖子按钮 -->
    <PostFab />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getPostDetail, likePost, unlikePost, deletePost as deletePostApi } from '@/api/post'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import PostFab from '@/components/PostFab.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const post = ref(null)
const comments = ref([])
const newComment = ref('')
const commentLoading = ref(false)

// 计算属性
const canEdit = computed(() => {
  return userStore.userInfo && post.value && userStore.userInfo.id === post.value.user.id
})

// 获取帖子详情
const fetchPostDetail = async () => {
  loading.value = true
  try {
    const response = await getPostDetail(route.params.id)
    if (response.code === 200) {
      post.value = response.data
      // 模拟评论数据
      comments.value = [
        {
          id: 1,
          content: '很棒的分享！',
          user: { id: 2, username: '张同学', avatar: '' },
          createTime: '2024-01-01T12:30:00Z',
          likesCount: 3,
          replies: [
            {
              id: 2,
              content: '谢谢支持！',
              user: { id: 1, username: '李同学', avatar: '' },
              createTime: '2024-01-01T12:35:00Z'
            }
          ]
        }
      ]
    }
  } catch (error) {
    // 如果获取失败，使用模拟数据
    post.value = {
      id: 1,
      title: '我的校园生活分享',
      content: '今天天气很好，和同学们一起去图书馆学习。图书馆里很安静，是个学习的好地方。我们一起讨论了课业问题，互相帮助，感觉很充实。\n\n午饭时间我们去了食堂，尝试了新的菜品，味道还不错。下午继续在图书馆看书，直到闭馆才离开。\n\n希望每一天都能这样充实地度过！',
      images: [
        'https://picsum.photos/600/400?random=1',
        'https://picsum.photos/600/400?random=2'
      ],
      user: {
        id: 1,
        username: '李同学',
        avatar: 'https://picsum.photos/50/50?random=1'
      },
      category: {
        id: 2,
        name: '生活分享'
      },
      likesCount: 15,
      commentsCount: 3,
      viewsCount: 120,
      isLiked: false,
      createTime: '2024-01-01T10:00:00Z'
    }
    
    comments.value = [
      {
        id: 1,
        content: '很棒的分享！看起来你的校园生活很充实呢～',
        user: { id: 2, username: '张同学', avatar: 'https://picsum.photos/40/40?random=2' },
        createTime: '2024-01-01T12:30:00Z',
        likesCount: 3,
        replies: [
          {
            id: 2,
            content: '谢谢！确实很享受这样的校园时光',
            user: { id: 1, username: '李同学', avatar: 'https://picsum.photos/32/32?random=1' },
            createTime: '2024-01-01T12:35:00Z'
          }
        ]
      },
      {
        id: 3,
        content: '图书馆确实是个好地方，我也经常去那里学习',
        user: { id: 3, username: '王同学', avatar: 'https://picsum.photos/40/40?random=3' },
        createTime: '2024-01-01T14:20:00Z',
        likesCount: 1,
        replies: []
      }
    ]
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow()
}

// 切换点赞
const toggleLike = async () => {
  try {
    if (post.value.isLiked) {
      await unlikePost(post.value.id)
      post.value.likesCount--
      post.value.isLiked = false
      ElMessage.success('已取消点赞')
    } else {
      await likePost(post.value.id)
      post.value.likesCount++
      post.value.isLiked = true
      ElMessage.success('点赞成功')
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
  }
}

// 分享帖子
const sharePost = () => {
  const url = window.location.href
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 编辑帖子
const editPost = () => {
  router.push(`/post/edit/${post.value.id}`)
}

// 删除帖子
const deletePost = async () => {
  try {
    await ElMessageBox.confirm('确定要删除这篇帖子吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deletePostApi(post.value.id)
    ElMessage.success('删除成功')
    router.push('/home')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  commentLoading.value = true
  try {
    // 这里调用API提交评论
    ElMessage.success('评论成功')
    newComment.value = ''
    // 重新获取评论列表
    fetchPostDetail()
  } catch (error) {
    console.error('评论失败:', error)
  } finally {
    commentLoading.value = false
  }
}

// 点赞评论
const likeComment = async (comment) => {
  try {
    // 这里调用API
    comment.likesCount = (comment.likesCount || 0) + 1
    ElMessage.success('点赞成功')
  } catch (error) {
    console.error('点赞失败:', error)
  }
}

// 回复评论
const replyComment = (comment) => {
  ElMessage.info('回复功能开发中...')
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/login')
}

onMounted(() => {
  fetchPostDetail()
})
</script>

<style scoped>
.post-detail {
  max-width: 800px;
  margin: 0 auto;
}

.skeleton-content {
  padding: 30px;
}

.post-content {
  margin-bottom: 20px;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 24px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.username {
  font-weight: 500;
  color: #303133;
}

.post-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.post-body {
  margin-bottom: 24px;
}

.post-title {
  color: #303133;
  margin-bottom: 16px;
  line-height: 1.4;
}

.post-text {
  color: #606266;
  line-height: 1.8;
  margin-bottom: 20px;
  white-space: pre-line;
}

.post-images {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
  margin-bottom: 20px;
}

.post-image {
  width: 100%;
  height: 200px;
  border-radius: 8px;
}

.post-actions {
  display: flex;
  gap: 24px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.comments-section {
  padding: 24px;
}

.comments-header {
  margin-bottom: 20px;
}

.comments-header h3 {
  color: #303133;
  margin: 0;
}

.comment-form {
  margin-bottom: 24px;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

.login-prompt {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 24px;
}

.login-prompt p {
  color: #909399;
  margin-bottom: 12px;
}

.comments-list {
  margin-top: 24px;
}

.empty-comments {
  text-align: center;
  padding: 40px 0;
}

.comment-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f8f9fa;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 500;
  color: #303133;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-text {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 8px;
}

.comment-actions {
  display: flex;
  gap: 16px;
}

.replies {
  margin-top: 16px;
  padding-left: 20px;
  border-left: 2px solid #f0f0f0;
}

.reply-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 12px;
}

.reply-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.reply-author {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.reply-text {
  color: #606266;
  font-size: 14px;
}

.reply-time {
  font-size: 12px;
  color: #909399;
}
</style>